#pragma once
#include "../common/net.hpp"
#include "../common/message.hpp"
#include <set>

namespace rpc
{
    namespace server
    {
        class ProviderManager
        {
        public:
            using ptr = std::shared_ptr<ProviderManager>;
            struct Provider
            {
                using ptr = std::shared_ptr<Provider>;
                std::mutex mtx;
                std::vector<std::string> methods;
                BaseConnection::ptr conn;
                Address host;
                Provider(const BaseConnection::ptr &c, const Address &addr) : conn(c), host(addr)
                {
                }
                void appendMethod(const std::string &method)
                {
                    std::unique_lock<std::mutex> lock(mtx);
                    methods.emplace_back(method);
                }
            };

            // 当服务提供者注册时候调用
            void addProvider(const BaseConnection::ptr &conn, const Address &host, const std::string &method)
            {
                Provider::ptr provider;
                {
                    std::unique_lock<std::mutex> lock(_mutex);
                    auto it = _conns.find(conn);
                    if (it == _conns.end())
                    {
                        provider = std::make_shared<Provider>(conn, host);
                        _conns.insert(std::make_pair(conn, provider));
                    }
                    else
                        provider = it->second;
                    auto &providers = _providers[method];
                    providers.insert(provider);
                }
                provider->appendMethod(method);
            }
            // 当一个服务提供者断开连接的时候，获取他的信息--用于进行服务下线通知
            Provider::ptr getProvider(const BaseConnection::ptr &c)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                auto it = _conns.find(c);
                if (it != _conns.end())
                    return it->second;
                return Provider::ptr();
            }

            // 当一个服务断开连接时候，删除它的关联信息
            void delProvider(const BaseConnection::ptr &c)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                auto it = _conns.find(c);
                if (it == _conns.end())
                {
                    return;
                }
                for (auto &method : it->second->methods)
                {
                    auto &providers = _providers[method];
                    providers.erase(it->second);
                }
                _conns.erase(it);
            }
            std::vector<Address> methodHosts(const std::string &method)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                auto it = _providers.find(method);
                if (it == _providers.end())
                {
                    return std::vector<Address>();
                }
                std::vector<Address> v;
                for (auto &provider : it->second)
                {
                    v.push_back(provider->host);
                }
                return v;
            }

        private:
            std::mutex _mutex;
            std::unordered_map<std::string, std::set<Provider::ptr>> _providers;
            std::unordered_map<BaseConnection::ptr, Provider::ptr> _conns;
        };

        class DiscoverManager
        {
        public:
            using ptr = std::shared_ptr<DiscoverManager>;
            struct Discoverer
            {
                using ptr = std::shared_ptr<Discoverer>;
                std::mutex mtx;
                BaseConnection::ptr conn;         // 服务发现者对应的客户端连接
                std::vector<std::string> methods; // 服务发现者发现的服务
                Discoverer(const BaseConnection::ptr &c) : conn(c)
                {
                }
                void appendMethod(const std::string &method)
                {
                    std::unique_lock<std::mutex> lock(mtx);
                    methods.emplace_back(method);
                }
            };
            Discoverer::ptr addDicoverer(const BaseConnection::ptr &conn, const std::string &method)
            {
                Discoverer::ptr discoverer;
                {
                    std::unique_lock<std::mutex> lock(_mutex);
                    auto it = _conns.find(conn);
                    if (it != _conns.end())
                    {
                        discoverer = it->second;
                    }
                    else
                    {
                        discoverer = std::make_shared<Discoverer>(conn);
                        _conns.insert(std::make_pair(conn, discoverer));
                    }
                    auto &discoverers = _discoverers[method];
                    discoverers.insert(discoverer);
                }
                discoverer->appendMethod(method);
                return discoverer;
            }

            // 发现者客户端断开连接时，删除服务发现者信息
            void delDiscoverer(const BaseConnection::ptr &conn)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                auto it = _conns.find(conn);
                if (it == _conns.end())
                {
                    return;
                }
                for (auto &method : it->second->methods)
                {
                    auto &discoverer = _discoverers[method];
                    discoverer.erase(it->second);
                }
                _conns.erase(it);
            }

            // 当有一个新的服务提供者上线，则进行上线通知
            void onlineNotify(const std::string &method, const Address &host)
            {
                return notify(method, host, ServiceOptype::SERVICE_ONLINE);
            }
            // 当有一个服务提供者断开连接，则进行下线通知
            void offlineNotify(const std::string &method, const Address &host)
            {
                return notify(method, host, ServiceOptype::SERVICE_OFFLINE);
            }

        private:
            void notify(const std::string &method, const Address &host, ServiceOptype optype)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                auto it = _discoverers.find(method);
                if (it == _discoverers.end())
                {
                    // 当前服务没有服务发现者
                    return;
                }
                auto msg_req = MessageFactory::create<ServiceRequest>();
                msg_req->setHost(host);///提供服务的主机
                msg_req->setid(UUID::uuid());
                msg_req->setMethod(method);
                msg_req->setmtype(Mtype::REQ_SERVICE);
                msg_req->setOptype(optype);
                for (auto &discoverer : it->second)
                {
                    if (discoverer->conn && discoverer->conn->connected())
                        discoverer->conn->send(msg_req);
                }
            }

        private:
            std::mutex _mutex;
            std::unordered_map<std::string, std::set<Discoverer::ptr>> _discoverers;
            std::unordered_map<BaseConnection::ptr, Discoverer::ptr> _conns;
        };

        class PDManager
        {
        public:
            using ptr = std::shared_ptr<PDManager>;
            PDManager() : 
            _providers(std::make_shared<ProviderManager>()) ,
            _discoverers(std::make_shared<DiscoverManager>()) 
            {}
            void onServiceRequest(const BaseConnection::ptr &conn, const ServiceRequest::ptr &msg) 
            {
                //服务操作请求
                //服务发现或者服务注册
                ServiceOptype optype = msg->optype();
                if(optype == ServiceOptype::SERVICE_REGISTRY)
                {
                    //服务注册：
                    //  1. 新增服务提供者；  2. 进行服务上线的通知
                    ILOG("%s : %d 注册服务，%s",msg->host().first.c_str(),msg->host().second,msg->method().c_str());
                    _providers->addProvider(conn,msg->host(),msg->method());
                    _discoverers->onlineNotify(msg->method(),msg->host());

                    return  registryResponse(conn, msg);
                }
                else if(optype == ServiceOptype::SERVICE_DISCOVERY)
                {
                    //服务发现：
                    //新增服务发现者
                    ILOG("客户端要进行 %s 服务发现！", msg->method().c_str());
                    _discoverers->addDicoverer(conn,msg->method());
                    return discoveryResponse(conn,msg);
                }
                else
                {
                    ELOG("收到服务操作请求，但是操作类型错误！");
                    return errorResponse(conn,msg);
                }
            }
            void onConnShutdown(const BaseConnection::ptr& conn)
            {
                auto provider = _providers->getProvider(conn);
                if(_providers.get() != nullptr)
                {
                    ILOG("%s:%d 服务下线", provider->host.first.c_str(), provider->host.second);
                    for(auto &method : provider->methods)
                    {
                        _discoverers->offlineNotify(method,provider->host);
                    }
                    _providers->delProvider(conn);
                }
                _discoverers->delDiscoverer(conn);
            }
        private:
            void errorResponse(const BaseConnection::ptr &conn, const ServiceRequest::ptr &msg) 
            {
                auto msg_rsp = MessageFactory::create<ServiceResponse>();
                msg_rsp->setid(msg->id());
                msg_rsp->setmtype(Mtype::RSP_SERVICE);
                msg_rsp->setOptype(ServiceOptype::SERVICE_UNKNOW);
                msg_rsp->setRcode(Rcode::RCODE_INVALID_OPTYPE);
                conn->send(msg_rsp);
            }
            void registryResponse(const BaseConnection::ptr& conn,const ServiceRequest::ptr& msg)
            {
                auto msg_rsp = MessageFactory::create<ServiceResponse>();
                msg_rsp->setid(msg->id());
                msg_rsp->setmtype(Mtype::RSP_SERVICE);
                msg_rsp->setOptype(ServiceOptype::SERVICE_REGISTRY);
                msg_rsp->setRcode(Rcode::RCODE_OK);
                conn->send(msg_rsp);
            }
            void discoveryResponse(const BaseConnection::ptr& conn,const ServiceRequest::ptr& msg)
            {
                auto msg_rsp = MessageFactory::create<ServiceResponse>();
                msg_rsp->setid(msg->id());
                msg_rsp->setmtype(Mtype::RSP_SERVICE);
                msg_rsp->setOptype(ServiceOptype::SERVICE_DISCOVERY);
                std::vector<Address> hosts = _providers->methodHosts(msg->method());
                if(hosts.empty())
                {
                    msg_rsp->setRcode(Rcode::RCODE_NOT_FOUND_SERVICE);
                    return conn->send(msg_rsp);
                }
                msg_rsp->setRcode(Rcode::RCODE_OK);
                msg_rsp->setMethod(msg->method());
                msg_rsp->setHost(hosts);
                conn->send(msg_rsp);
            }
        private:
            ProviderManager::ptr _providers;
            DiscoverManager::ptr _discoverers;
        };
    }
}